package com.cxh.rmsq.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.cxh.rmsq.BuildConfig;
import com.cxh.rmsq.contact.PhoneContactManager;
import com.cxh.rmsq.im.IMManager;
import com.cxh.rmsq.model.Resource;
import com.cxh.rmsq.model.Status;
import com.cxh.rmsq.qrcode.SealQrCodeUISelector;
import com.cxh.rmsq.ui.BaseActivity;
import com.cxh.rmsq.ui.activity.self.UnderModeActivity;
import com.cxh.rmsq.utils.CheckPermissionUtils;
import com.cxh.rmsq.utils.SearchUtils;
import com.cxh.rmsq.utils.StatusBarUtil;
import com.cxh.rmsq.utils.ToastUtils;
import com.cxh.rmsq.utils.dialog.LoginPopup;
import com.cxh.rmsq.utils.log.SLog;
import com.cxh.rmsq.viewmodel.SplashViewModel;

import com.cxh.rmsq.R;
import com.lxj.xpopup.XPopup;
import com.umeng.commonsdk.UMConfigure;

import java.util.HashMap;

import io.rong.callkit.RongCallKit;
import io.rong.callkit.util.SPUtils;
import io.rong.imkit.GlideKitImageEngine;
import io.rong.imkit.IMCenter;
import io.rong.imkit.RongIM;
import io.rong.imkit.config.RongConfigCenter;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.push.RongPushClient;

public class SplashActivity extends BaseActivity {
    private Uri intentUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RongCallKit.setMainPageActivityClass(new String[] {MainActivity.class.getName()});
        // 处理小米手机按 home 键重新进入会重新打开初始化的页面
        if (!this.isTaskRoot()) {
            Intent mainIntent = getIntent();
            String action = mainIntent.getAction();
            if (mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
                    && action.equals(Intent.ACTION_MAIN)) {
                finish();
                return;
            }
        }
        getWindow().setBackgroundDrawable(null);
        setContentView(R.layout.activity_splash);
//        initStatusBar();

        Intent intent = getIntent();
        if (intent != null) {
            intentUri = intent.getData();
            recordHWNotificationEvent(intent);
        }
//        initViewModel();
        boolean firstOpenApp = com.blankj.utilcode.util.SPUtils.getInstance().getBoolean("firstOpenApp",true);
        if (firstOpenApp) {
//                            startActivity<WelcomeActivity>()
//                            finish()
            new XPopup.Builder(this)
                    .dismissOnTouchOutside(false)
                    .dismissOnBackPressed(false)
                    .asCustom(new LoginPopup(this, 1, new LoginPopup.onClick() {
                        @Override
                        public void click(@NonNull String s, @NonNull String s1, @NonNull String s2, @NonNull String s3, @NonNull String s4) {
                            if (TextUtils.isEmpty(SPUtils.get(SplashActivity.this,"accessToken","").toString())){
                                goToLogin();
                            }else {
                                goToMain();
                            }
                            initIM();
                        }
                    }))
                    .show();
        }else {
            if (TextUtils.isEmpty(SPUtils.get(SplashActivity.this,"accessToken","").toString())){
                goToLogin();
            }else {
                goToMain();
            }
            initIM();
        }

    }


    private void initIM(){
        HashMap<String, Integer> map = new HashMap<>();
        int id = io.rong.imkit.R.drawable.rc_file_icon_pdf;
        map.put("doc", R.drawable.doc_icon);
        map.put("mp3", R.drawable.mp3_icon);
        map.put("pdf", R.drawable.pdf_icon);
        map.put("rmvb", R.drawable.rmvb_icon);
        map.put("default", R.drawable.default_icon);
        map.put("error", 123);
        RongConfigCenter.conversationConfig().registerFileSuffixTypes(map);

        IMManager.getInstance().init(getApplication());
        RongConfigCenter.featureConfig()
                .setKitImageEngine(
                        new GlideKitImageEngine() {
                            @Override
                            public void loadConversationListPortrait(
                                    @NonNull Context context,
                                    @NonNull String url,
                                    @NonNull ImageView imageView,
                                    Conversation conversation) {
                                @DrawableRes
                                int resourceId = io.rong.imkit.R.drawable.rc_default_portrait;
                                switch (conversation.getConversationType()) {
                                    case GROUP:
                                        resourceId =
                                                io.rong.imkit.R.drawable.rc_default_group_portrait;
                                        break;
                                    case CUSTOMER_SERVICE:
                                        resourceId =
                                                io.rong.imkit.R.drawable.rc_cs_default_portrait;
                                        break;
                                    case CHATROOM:
                                        resourceId =
                                                io.rong
                                                        .imkit
                                                        .R
                                                        .drawable
                                                        .rc_default_chatroom_portrait;
                                        break;
                                }
                                Glide.with(imageView)
                                        .load(url)
                                        .placeholder(resourceId)
                                        .error(resourceId)
                                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                        .into(imageView);
                            }

                            @Override
                            public void loadConversationPortrait(
                                    @NonNull Context context,
                                    @NonNull String url,
                                    @NonNull ImageView imageView,
                                    Message message) {
                                @DrawableRes
                                int resourceId = io.rong.imkit.R.drawable.rc_default_portrait;
                                switch (message.getConversationType()) {
                                    case CUSTOMER_SERVICE:
                                        if (Message.MessageDirection.RECEIVE
                                                == message.getMessageDirection())
                                            resourceId =
                                                    io.rong.imkit.R.drawable.rc_cs_default_portrait;
                                        break;
                                }
                                Glide.with(imageView)
                                        .load(url)
                                        .placeholder(resourceId)
                                        .error(resourceId)
                                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                        .into(imageView);
                            }
                        });
        RongIM.getInstance().setVoiceMessageType(IMCenter.VoiceMessageType.HighQuality);

        // UMeng初始化
        UMConfigure.preInit(this, BuildConfig.SEALTALK_UMENG_APPKEY, null);

        PhoneContactManager.getInstance().init(this);
        CheckPermissionUtils.setPermissionRequestListener(this);

        SearchUtils.init(this);
    }

    private void recordHWNotificationEvent(Intent intent) {
        if (Build.MANUFACTURER.equalsIgnoreCase("HUAWEI")
                && intent.getData() != null
                && "true".equals(intent.getData().getQueryParameter("isFromPush"))) {
            RongPushClient.recordHWNotificationEvent(intent);
        }
    }

    private void initStatusBar() {
        // 这里注意下 因为在评论区发现有网友调用setRootViewFitsSystemWindows 里面 winContent.getChildCount()=0 导致代码无法继续
        // 是因为你需要在setContentView之后才可以调用 setRootViewFitsSystemWindows
        // 当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtil.setRootViewFitsSystemWindows(this, true);
        // 设置状态栏透明
        StatusBarUtil.setTranslucentStatus(this);
        StatusBarUtil.setStatusBarDarkTheme(this,true);
        // 一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        // 所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
//        if (!StatusBarUtil.setStatusBarDarkTheme(this, false)) {
//            // 如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
//            // 这样半透明+白=灰, 状态栏的文字能看得清
//            StatusBarUtil.setStatusBarColor(this, 0x000000);
//        }
    }

    /** 初始化ViewModel */
    private void initViewModel() {
        SplashViewModel splashViewModel = ViewModelProviders.of(this).get(SplashViewModel.class);
        splashViewModel
                .getAutoLoginResult()
                .observe(
                        this,
                        new Observer<Boolean>() {
                            @Override
                            public void onChanged(Boolean result) {
                                SLog.d("ss_auto", "result = " + result);

                                if (result) {
                                    goToMain();
                                } else {
                                    if (intentUri != null) {
                                        ToastUtils.showToast(
                                                R.string.seal_qrcode_jump_without_login);
                                    }
                                    goToLogin();
                                }
                            }
                        });
    }

    private void goToMain() {
        if (TextUtils.isEmpty(SPUtils.get(this, "UNDER_PWD", "").toString())) {
            startActivity(new Intent(this, MainActivity.class));
        }else {
            startActivity(new Intent(this, UnderModeActivity.class));
        }
        if (intentUri != null) {
            goWithUri();
        } else {
            finish();
        }
    }

    private void goToLogin() {
        startActivity(new Intent(this, LoginActivity.class));
        SPUtils.put(this, "UNDER_PWD", "");//取消未成年
        finish();
    }

    /** 通过 uri 进行跳转 */
    private void goWithUri() {
        String uri = intentUri.toString();

        // 判断是否是二维码跳转产生的 uri
        SealQrCodeUISelector uiSelector = new SealQrCodeUISelector(this);
        LiveData<Resource<String>> result = uiSelector.handleUri(uri);

        result.observe(
                this,
                new Observer<Resource<String>>() {
                    @Override
                    public void onChanged(Resource<String> resource) {
                        if (resource.status != Status.LOADING) {
                            result.removeObserver(this);
                        }

                        if (resource.status == Status.SUCCESS) {
                            finish();
                        }
                    }
                });
    }
}
